package cn.doctorpda.conference.ui.checked;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;

import cn.doctorpda.conference.R;
import cn.doctorpda.conference.adapter.CheckMeetingAdapter;
import cn.doctorpda.conference.bean.Msg;
import cn.doctorpda.conference.bean.checkmeeting.CheckMeetingInfoItem;
import cn.doctorpda.conference.bean.checkmeeting.DataCheckMeetingInfo;
import cn.doctorpda.conference.bean.checkmeeting.DataProvinceInfo;
import cn.doctorpda.conference.bean.checkmeeting.DataSubjectInfo;
import cn.doctorpda.conference.event.MainEvent;
import cn.doctorpda.conference.presenter.CheckMeetingPresenter;
import cn.doctorpda.conference.presenter.GetProvincePresenter;
import cn.doctorpda.conference.presenter.GetSubjectPresenter;
import cn.doctorpda.conference.ui.BaseFragment;
import cn.doctorpda.conference.ui.common.DetailActivity;
import cn.doctorpda.conference.utils.L;
import cn.doctorpda.conference.utils.T;
import cn.doctorpda.conference.view.callbackview.ICheckMeetingPageView;
import cn.doctorpda.conference.view.callbackview.IProvinceView;
import cn.doctorpda.conference.view.callbackview.ISubjectView;
import cn.doctorpda.conference.view.recyclerview.XRecylcerView;
import cn.doctorpda.conference.view.wheelview.widget.WheelViewDialog;
import okhttp3.Call;

/**
 * Created by huangjinlong on 2016/5/17.
 */
public class CheckFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, XRecylcerView.LoadingListener, View.OnClickListener, ICheckMeetingPageView, IProvinceView, ISubjectView {

    private SwipeRefreshLayout checkRefreshLayout;
    private XRecylcerView checkXRecylcerView;
    private CheckMeetingAdapter mAdapter;
    private CheckMeetingPresenter checkMeetingPresenter;
    private int pageNumber = 1;
    private String strProvinceName = "", strSubjectId = "", strDate = "", type = "";


    private LinearLayout ll_address, ll_subject, ll_date;
    private TextView tv_date, tv_subject, tv_address;
    private GetProvincePresenter provincePresenter;
    private GetSubjectPresenter subjectPresenter;

    private Calendar c = Calendar.getInstance();
    private String mYear, mMonth;

    private LinearLayout ll_no_data;
    private Boolean isNormalSelected;
    private TextView tv_no_data;
    private ImageView imv_no_data;

    public static CheckFragment newInstance() {
        CheckFragment fragment = new CheckFragment();
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mAdapter = new CheckMeetingAdapter();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_check, container, false);
        initView(view);
        initData();
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (isNormalSelected) {
                L.d("不该知晓");
                mYear = c.get(Calendar.YEAR) + "";
                mMonth = c.get(Calendar.MONTH) + 1 + "";
                strProvinceName = "";
                strSubjectId = "";
                strDate = "";
                type = "";
                tv_address.setText("选择地区");
                tv_subject.setText("选择学科");
                tv_date.setText("选择时间");
                checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
            }
            L.i("状态", "显示");
        } else {
            L.i("状态", "不显示");
            isNormalSelected = true;
        }
    }

    //首页联动
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetfilterEvent(MainEvent mainEvent) {
        if (mainEvent == null) {
            return;
        }
        try {
            Thread.sleep(100);
            isNormalSelected = false;
            strProvinceName = mainEvent.getConProvince();
            type = mainEvent.getConType();
            if (strProvinceName.trim().isEmpty()) {
                tv_address.setText("所有地区");
            } else {
                tv_address.setText(strProvinceName);
            }
            checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    @Override
    public String getPageName() {
        return "CheckFragment";
    }

    private void initData() {
        mYear = c.get(Calendar.YEAR) + "";
        mMonth = c.get(Calendar.MONTH) + 1 + "";
        checkMeetingPresenter = new CheckMeetingPresenter(this);
        checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
        provincePresenter = new GetProvincePresenter(this);
        subjectPresenter = new GetSubjectPresenter(this);
    }

    private void initView(View view) {

        checkRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.check_refresh);
        checkXRecylcerView = (XRecylcerView) view.findViewById(R.id.check_loadmore);
        checkXRecylcerView.setHasFixedSize(true);
        checkXRecylcerView.setLoadingListener(this);
        checkXRecylcerView.setLoadingMoreEnabled(true);
        checkRefreshLayout.setOnRefreshListener(this);
        checkXRecylcerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        checkXRecylcerView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();

        ll_address = (LinearLayout) view.findViewById(R.id.ll_choose_address);
        ll_subject = (LinearLayout) view.findViewById(R.id.ll_choose_subject);
        ll_date = (LinearLayout) view.findViewById(R.id.ll_choose_date);

        tv_date = (TextView) view.findViewById(R.id.tv_date);
        tv_address = (TextView) view.findViewById(R.id.tv_address);
        tv_subject = (TextView) view.findViewById(R.id.tv_subject);

        ll_address.setOnClickListener(this);
        ll_date.setOnClickListener(this);
        ll_subject.setOnClickListener(this);

        mAdapter.setOnItemClickListener(new CheckMeetingAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, CheckMeetingInfoItem data) {
                L.i("地址url" + data.getURL());
                DetailActivity.startActivity(getActivity(), data.getNAME(), data.getID(), "conference", data.getURL());
            }
        });

        ll_no_data = (LinearLayout) view.findViewById(R.id.ll_no_data);
        tv_no_data = (TextView) view.findViewById(R.id.tv_no_data_show);
        imv_no_data = (ImageView) view.findViewById(R.id.imv_no_data_show);
    }

    @Override
    public void onLoadMore() {
        ++pageNumber;
        checkMeetingPresenter.getCheckMeetingData(pageNumber + "", "10", strProvinceName, strSubjectId, strDate, type);
    }

    @Override
    public void onRefresh() {
        pageNumber = 1;
        L.i("刷新" + strProvinceName + strSubjectId + strDate);
        checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);

        ll_no_data.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ll_choose_address:
                provincePresenter.getProvinceData();
                break;
            case R.id.ll_choose_subject:
                subjectPresenter.getSubjectData();
                break;
            case R.id.ll_choose_date:
                DateDialogFragment aPick = DateDialogFragment.newInstance(mYear, mMonth);
                aPick.show(getActivity().getSupportFragmentManager(), null);

                aPick.setOnDataPickListener(new DateDialogFragment.OnDataPickListener() {
                    @Override
                    public void setOnDataPickListener(String year, String month) {
                        if (year.trim().isEmpty() && month.trim().isEmpty()) {
                            mYear = c.get(Calendar.YEAR) + "";
                            mMonth = c.get(Calendar.MONTH) + 1 + "";
                            strDate = "";
                            tv_date.setText("所有年份");
                        } else {
                            if (month.equals("不限")) {
                                mYear = year;
                                mMonth = c.get(Calendar.MONTH) + 1 + "";
                                strDate = year;
                                tv_date.setText(year + "年" + "全年");
                            } else {
                                mYear = year;
                                mMonth = month;
                                strDate = year + "-" + month;
                                tv_date.setText(year + "年" + month + "月");
                            }

                        }
                        checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
                    }
                });

                break;
        }


    }

    @Override
    public void setPageRefreshResult(Msg msg, DataCheckMeetingInfo data) {
        // 设置当前刷新数，当下拉刷新的时候置为0，上拉加载时已经初始化
        checkXRecylcerView.setPreviousTotal(0);
        // 设置是否还有更多
        checkXRecylcerView.setIsnomore(false);
        checkRefreshLayout.setRefreshing(false);
        mAdapter.clear();
        if (data != null) {
            if (data.getPAGE().getList().isEmpty()) {
                ll_no_data.setVisibility(View.VISIBLE);
                tv_no_data.setVisibility(View.VISIBLE);
                imv_no_data.setBackgroundResource(R.drawable.nodata);
                tv_no_data.setText("");
            } else {
                ll_no_data.setVisibility(View.INVISIBLE);
            }
            mAdapter.addAll(data.getPAGE().getList());
        } else {
            ll_no_data.setVisibility(View.VISIBLE);
            tv_no_data.setVisibility(View.INVISIBLE);
            imv_no_data.setBackgroundResource(R.drawable.shibai);
        }
    }

    @Override
    public void setPageLoadResult(Msg msg, DataCheckMeetingInfo data) {
        checkXRecylcerView.loadMoreComplete();
        if (data != null)
            mAdapter.addAll(data.getPAGE().getList());
    }

    @Override
    public void setPageError(Call call, Exception e) {
        mAdapter.clear();
        checkRefreshLayout.setRefreshing(false);
        ll_no_data.setVisibility(View.VISIBLE);
        tv_no_data.setVisibility(View.INVISIBLE);
        imv_no_data.setBackgroundResource(R.drawable.shibai);
    }

    //省
    @Override
    public void setProvinceView(Msg msg, final DataProvinceInfo data) {
        final ArrayList<String> list = new ArrayList<String>();
        list.add("所有地区");
        for (int i = 0; i < data.getPROVINCES().size(); i++) {

            list.add(data.getPROVINCES().get(i).getNAME());
        }
        ProvinceDialogFragment pPick = ProvinceDialogFragment.newInstance(list, "地区");
        pPick.show(getActivity().getSupportFragmentManager(), null);

        pPick.setOnDataPickListener(new ProvinceDialogFragment.OnWheelPickListener() {
            @Override
            public void setOnDataPickListener(String content, int pos) {
                tv_address.setText(content);

                if (content.equals("所有地区")) {
                    strProvinceName = "";
                    checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
                } else {
                    strProvinceName = content;
                    checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
                }

            }
        });

//        WheelViewDialog dialog = new WheelViewDialog(getContext());
//        dialog.setItems(list).setDialogStyle(Color
//                .parseColor("#888888")).setCount(3).show();
//
//        dialog.setOnDialogItemClickListener(new WheelViewDialog.OnDialogItemClickListener() {
//            @Override
//            public void onItemClick(int position, Object s) {
//
//                if (position == 0) {
//                    strProvinceName = "";
//                    tv_address.setText("所有地区");
//                    checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
//                } else {
//                    strProvinceName = data.getPROVINCES().get(position - 1).getNAME();
//                    tv_address.setText(list.get(position));
//                    checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
//                }
//
//            }
//        });
    }

    //学科
    @Override
    public void setSubjectView(Msg msg, final DataSubjectInfo data) {
        final ArrayList<String> listSub = new ArrayList<String>();
        listSub.add("所有学科");
        for (int i = 0; i < data.getFIRSTCATEGORYS().size(); i++) {

            listSub.add(data.getFIRSTCATEGORYS().get(i).getNAME());
        }
        ProvinceDialogFragment sPick = ProvinceDialogFragment.newInstance(listSub, "学科");
        sPick.show(getActivity().getSupportFragmentManager(), null);

        sPick.setOnDataPickListener(new ProvinceDialogFragment.OnWheelPickListener() {
            @Override
            public void setOnDataPickListener(String content, int pos) {
                tv_subject.setText(content);

                if (content.equals("所有学科")) {
                    strSubjectId = "";
                    T.showShort(getContext(), "选择的学科" + strSubjectId);
                    checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
                } else {
                    strSubjectId = data.getFIRSTCATEGORYS().get(pos - 1).getID();
                    ;
                    checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
                }

            }
        });


//        WheelViewDialog dialogSub = new WheelViewDialog(getContext());
//        dialogSub.setTitle("学科").setItems(listSub).setButtonText("确定").setDialogStyle(Color
//                .parseColor("#6699ff")).setCount(3).show();
//        dialogSub.setOnDialogItemClickListener(new WheelViewDialog.OnDialogItemClickListener() {
//            @Override
//            public void onItemClick(int position, Object s) {
//                if (position == 0) {
//                    tv_subject.setText("所有学科");
//                    strSubjectId = "";
//                    checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
//                } else {
//                    strSubjectId = data.getFIRSTCATEGORYS().get(position - 1).getID();
//                    tv_subject.setText(listSub.get(position));
//                    checkMeetingPresenter.getCheckMeetingData("1", "10", strProvinceName, strSubjectId, strDate, type);
//
//                }
//
//            }
//        });
    }

    @Override
    public void setResultError(Call call, Exception e) {

    }
}
